﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.interfaces;
using System.Web.UI.WebControls;
using System.Web.UI;
using umbraco.editorControls.userControlGrapper;
using Core.Module;
namespace Module.MultiSiteFields.Controls.DynamicTreePicker
{
    public class PropertyDataEditor:WebControl, IDataEditor
    {
        private IDataType DataType;
         
        public PropertyDataEditor(IDataType dataType)
        {
            DataType = dataType;
        }
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Editor c = Page.LoadControl("~/umbraco/ism/fields/dynamictreepicker/editor.ascx") as Editor;            
            c.DataType = DataType;
            c.Value = DataValue;
            c.PreValue = DataPreValue;
            this.Controls.Add(c);
        }
        
        public Control Editor
        {
            get { return this; }
        }
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        protected DynamicTreePreValue DataPreValue
        {
            get
            {
                umbraco.cms.businesslogic.datatype.PreValue pvalue = (DataType.PrevalueEditor as PropertyPrevaluesEditor).PreValue;
                return pvalue == null || string.IsNullOrEmpty(pvalue.Value) ? null : pvalue.Value.FromJson<DynamicTreePreValue>();
            }
        }
           

        protected DynamicTreeValue DataValue{
            get {
                string svalue = (DataType.Data.Value as string);
                DynamicTreeValue dtv = svalue.FromXml<DynamicTreeValue>();
                if (dtv == null)
                {
                    dtv = new DynamicTreeValue();
                    DynamicTreeValue.Node node = svalue.FromXml<DynamicTreeValue.Node>();
                    if (node!=null) dtv.Nodes = new DynamicTreeValue.Node[] { node };
                }
                return dtv;
            }
            set {

                if (value == null || value.Nodes.Length == 0) DataType.Data.Value = null;
                else if (DataPreValue!=null && DataPreValue.MaxAmountItems==1) DataType.Data.Value = value.Nodes[0].ToXml();
                else DataType.Data.Value = value.ToXml();
            }
    }

        public void Save()
        {
            DynamicTreeValue value = (this.Controls[0] as Editor).Value as DynamicTreeValue;
            DataValue = value;
        }

        public bool ShowLabel
        {
            get { return (DataType.PrevalueEditor as PropertyPrevaluesEditor).ShowLabel; }
        }

        public bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        



    }

}
